<template>
    <Layout>
        <Row :gutter="16" class="query-form" style="margin-left: 10px">
            <span style="font-size: 16px">任务书完成情况</span>
            <Button class="ivu-btn-reset" @click="goback" icon="md-arrow-back">返回</Button>
						<Button size="large" class="ivu-btn-query" icon="md-cloud-download" :loading="exportLoading" @click="exportExcel">导出完成情况</Button>
        </Row>
        <Table ref='table' row-key="rowKey" :load-data="handleLoadData" :height="tableHeight" no-data-text="没有查询到相关数据!" :span-method="handleSpan" :loading='pageStatus.loading'
               border :columns="columns1" :data="dataTable">
            <template slot-scope="{ row, index }" slot="signPeoperNum">
                <div v-if="view || !row.contentId">{{row.signPeoperNum}}</div>
                <InputNumber v-else :min='0' :max="1000" v-model="row.signPeoperNum" style="width: 100%"></InputNumber>
            </template>
						<template slot-scope="{ row, index }" slot="signBookNum">
						    <div v-if="view || !row.contentId">{{row.signBookNum}}</div>
						    <InputNumber v-else :min='0' :max="1000" v-model="row.signBookNum" style="width: 100%"></InputNumber>
						</template>
            <template slot-scope="{ row, index }" slot="completionDesc">
                <div v-if="view || !row.contentId">{{row.completionDesc}}</div>
                <Input v-else type="textarea" :autosize="{minRows:2,maxRows:5}" show-word-limit :maxlength="200" v-model="row.completionDesc" />
            </template>
            <template slot-scope="{ row, index }" slot="notes">
                <div v-if="view || !row.contentId">{{row.notes}}</div>
                <Input v-else type="textarea" :autosize="{minRows:2,maxRows:5}" show-word-limit :maxlength="200" v-model="row.notes" />
            </template>
						<template slot-scope="{ row, index }" slot="action">
							<div v-if="view || !row.contentId"></div>
						  <Button v-else size="small" type="primary" @click="saveEvaluate(row,index)">保存</Button>
						</template>
        </Table>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {formatDate} from '@/tools/index'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';

    export default {
        components: {cascaderDom},
        data() {
            return {
                ...this.createCommonDataField(),
                columns1: [
                    // {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    { key:'taskType',title: '任务类型',  align: 'center', minWidth: 120 },
                    { key:'num',title: '序号',  align: 'center', width: 80,tree: true},
                    { key:'taskContent',title: '任务内容',  align: 'center', minWidth: 160,tooltip:true },
										{ key:'monthName',title: '月份',  align: 'center', minWidth: 80},
										{ slot:'signPeoperNum',title: '任务书签订人数',  align: 'center', minWidth: 80,  },
										{ slot:'signBookNum',title: '任务书签订家数',  align: 'center', minWidth: 80,  },
                    { slot:'completionDesc',title: '完成情况',  align: 'center', minWidth: 140,  },
                    { slot:'notes',title: '备注',  align: 'center', minWidth: 140,  },
                    {title: '更新时间', width: 100, align: 'center', key:'updateDate',render:this.renderCellDate},
                    {title: '填报人', width: 100, align: 'center', key:'updateUserName'},
										{title: '操作', width: 65, align: 'center',  slot: 'action'},
                ],
                tableHeight: 10,
                // api
                saveUrl: Api.batchUpdateTaskBookContent,
								getAllByContentId: Api.updateTaskBookContent.replace('/content/update','/evaluate/getAllByContentId'),
								updateUrl: Api.updateTaskBookContent.replace('/content','/evaluate'),
								exportUrl:Api.updateTaskBookContent.replace('/content/update','/evaluate/export'),
                currentUser: JSON.parse(sessionStorage('userId').get('userId')),

                view: this.$attrs.view,
								_dataTable:[],
								exportLoading: false
            }
        },
				watch:{
					dataTable:function(val){
						// debugger
						// val.forEach(e=>{
						
						// })
					}
				},
        async mounted() {
            this.tableHeight = window.innerHeight -135 - 50
            this.query();
        },
        methods: {
            ...pageCommonFunction,
            goback(){
                this.$emit("close",true);
            },
						exportExcel() {
						    this.exportLoading = true
						    this.$http.get(this.exportUrl+'/'+this.$attrs.taskBook.id, {
						        responseType: 'blob'      //告诉服务器我们需要的响应格式
						    }).then((res) => {
						        const aLink = document.createElement("a");
						        let blob = new Blob([res.data], {
						            type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
						        });
						        aLink.href = URL.createObjectURL(blob)
						        aLink.download = "任务书进展.xlsx" //标题
						        aLink.click()
						        document.body.appendChild(aLink)
						        this.exportLoading = false
						    })
						},
						 handleLoadData (item, callback) {
							 if (!item._showView) {
							 	this.$http.get(this.getAllByContentId+'/'+ item.id).then((res) => {
									 res.data.data.forEach(e=>{
										 e._contentId = e.contentId
										 e.rowKey= item.id + e.id
										 e.projectId = item.projectId
										 e.taskTypeNum = item.taskTypeNum
										 e.taskType = item.taskType
										 e.num = item.num
										 e.taskContent = item.taskContent
										 e._showView = true
										 e._loading=false
										 e.children=[]
									 })
									 let dataTable = []
									 this._dataTable.forEach(e=>{
										 if (e.id == item.id) {
											 // dataTable.push({
												//  ...e,
												//  _showView: true
											 // })
											 res.data.data.forEach(n=>{
												 dataTable.push(n)
											 })
										 } else {
											 dataTable.push(e)
										 }
									 })
									 this.dataTable = this.getTableDate(dataTable)
							 	})
							 } else{
								 this.dataTable = this.getTableDate(this._dataTable)
							 }
							 callback([])
						},
						        
            handleSpan ({ row, column, rowIndex, columnIndex }) {
                if (columnIndex === 0) {
                    let x = row.mergeColumn === 0 ? 0:row.mergeColumn
                    let y = row.mergeColumn === 0 ? 0:1
                    return [x, y]
                } else if (columnIndex === 1 || columnIndex === 2) {
										let x = row.mergeColumn1 === 0 ? 0:row.mergeColumn1
										let y = row.mergeColumn1 === 0 ? 0:1
										return [x, y]
                } 
            },
						getTableDate(dataTable){
							let projectIds = []
							 let contentIds = []
							dataTable.forEach(e => {
							    if(!projectIds.includes(e.projectId)){
							        projectIds.push(e.projectId)
							    }
									if(e._contentId && !contentIds.includes(e._contentId)){
									    contentIds.push(e._contentId)
									}
							})
							let nameNums = []
							//将names数组中的 name值设置默认合并0个单元格,放到 nameNums中
							projectIds.forEach(e => {
							    nameNums.push({projectId:e,num:0})
							})
							
							let monthNums = []
							contentIds.forEach(e => {
							    monthNums.push({_contentId:e,num:0})
							})
							//计算每种 name值所在行需要合并的单元格数
							dataTable.forEach(e => {
							    nameNums.forEach(n => {
							        if(e.projectId === n.projectId){
							            n.num++
							        }
							    })
									monthNums.forEach(n => {
									    if(e._contentId === n._contentId){
									        n.num++
									    }
									})
							})
							dataTable.forEach(e => {
								if (!e._contentId) {
									e.rowKey = e.id
									e._loading=false
									e.children=[]
									e.updateDate = null
									e.updateUserName = null
								} 
							    // if (!e.completionProgress) {
							    //     e.updateDate = null
							    //     e.updateUserName = null
							    // }
							    nameNums.forEach(n => {
							        if(e.projectId === n.projectId){
							            if(projectIds.includes(e.projectId)){
							                e.mergeColumn = n.num
							                //删除已经设置过的值(防止被合并的单元格进到这个 if 语句中)
							                projectIds.splice(projectIds.indexOf(n.projectId),1)
							            } else {
							                //被合并的单元格设置为 0
							                e.mergeColumn = 0
							            }
							        }
							    })
						
									monthNums.forEach(n => {
									    if(e._contentId === n._contentId){
									        if(contentIds.includes(e._contentId)){
									            e.mergeColumn1 = n.num
									            //删除已经设置过的值(防止被合并的单元格进到这个 if 语句中)
									            contentIds.splice(contentIds.indexOf(n._contentId),1)
									        } else {
									            //被合并的单元格设置为 0
									            e.mergeColumn1 = 0
									        }
									    }
									})
							})
							return dataTable
						},
            query() {
                this.$http.get(Api.queryTaskBookContent+'/'+ this.$attrs.taskBook.id).then((res) => {
                    this.dataTable.splice()
										 this._dataTable = res.data.data
                    this.dataTable = this.getTableDate(res.data.data)
                })
            },

						saveEvaluate(row,index){
							row.updateDate= new Date(),
							row.updateUserId= this.currentUser.userId,
							row.updateOrgId= this.currentUser.orgInfo.orgId,
							row.updateUserName= this.currentUser.userName,
							this.$http.put(this.updateUrl, row).then((res) => {
							    if (res.data.status === 200) {
							        this.$Message.success('保存成功');
							        this.dataTable[index] = row
							    } else if (res.data.status === 201) {
							        this.$Message.error(res.data.msg);
							    }
							}).catch(e => {
							    this.$Message.error('保存失败')
							})
							
						},
            submit() {
                let data = []
                let completionProgress = 0
                this.dataTable.forEach(item=>{
                    if (item.completionProgress || item.completionDesc || item.completionStep) {
                        // item.updateDate = new Date()
                        // item.updateUserId = this.currentUser.userId
                        // item.updateOrgId = this.currentUser.orgInfo.orgId;
                        // item.updateUserName = this.currentUser.userName
                        completionProgress = this.NumberAdd(completionProgress,item.completionProgress? item.completionProgress :0)
                        data.push({
                            ...item,
                            updateDate: new Date(),
                            updateUserId: this.currentUser.userId,
                            updateOrgId: this.currentUser.orgInfo.orgId,
                            updateUserName: this.currentUser.userName,
                        })
                    }
                })
                let progress = this.NumberDiv(completionProgress,this.dataTable.length,2)
                if (data.length > 0) {
                    let decompose = {
                        contents: data,
                        progress: progress,
                        id: this.$attrs.taskBook.id,
                    }
                    this.$Modal.confirm({
                        title: '提示',
                        content: '<p>是否要提交？</p>',
                        onOk: () => {
                            this.$http.put(this.saveUrl, decompose).then((res) => {
                                if (res.data.status === 200) {
                                    this.$Message.success('保存成功');
                                    this.query()
                                } else if (res.data.status === 201) {
                                    this.$Message.error(res.data.msg);
                                }
                            }).catch(e => {
                                this.$Message.error('保存失败')
                            })

                        },
                        onCancel: () => {
                        }
                    });
                } else {
                    this.$Message.error('至少要填写一项任务的完成进度，才能提交')
                }
            },
        }
    }
</script>

<style lang='css' scoped>
    .ivu-form-item {
        padding-right: 20px;
    }

    .query-form-el, .ivu-date-picker, .ivu-input-wrapper {
        width: 100%;
    }

</style>